﻿using Apps.BLL.HC;
using Apps.Common;
using Apps.Locale;
using Apps.Models;
using Apps.Web.Core;
using Microsoft.Practices.Unity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.EnterpriseServices.Internal;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Wantn.FIS.Enum;

namespace Apps.Web.Areas.HC.Controllers
{
    public class HC_FORMController : BaseController
    {
        HC_EXTEND_FIELD_BLL bll = new HC_EXTEND_FIELD_BLL();
        HC_ITEM_EXTEND_REL_BLL relBll = new HC_ITEM_EXTEND_REL_BLL();
        HC_ITEMS_BLL itemsBll = new HC_ITEMS_BLL();
        HC_FORM_BLL formBll = new HC_FORM_BLL();
        readonly HC_FORM_REFERENCE_VALUE_BLL fvBll = new HC_FORM_REFERENCE_VALUE_BLL();
        readonly HC_EXAMINE_BLL examineBll = new HC_EXAMINE_BLL();

        ValidationErrors errors = new ValidationErrors();
        [SupportFilter]
        public ActionResult Index()
        {
            return View();
        }
        [SupportFilter(ActionName = "Index")]
        [HttpPost]
        public string GetItemList()
        {
            string queryStr = Utils.ObjectToStr(Request["queryStr"]);
            List<HC_ITEMS> itemList = itemsBll.GetList(queryStr);
            return JsonConvert.SerializeObject(itemList);
        }

        [SupportFilter(ActionName = "Index")]
        public string GetList()
        {
            string beginTime = Utils.ObjectToStr(Request["beginTime"]);
            string endTime = Utils.ObjectToStr(Request["endTime"]);
            int formState = Utils.ObjToInt(Request["formState"], -2);
            string itemId = Utils.ObjectToStr(Request["itemId"]);
            int pageSize = Utils.ObjToInt(Request["rows"], 15);
            int pageIndex = Utils.ObjToInt(Request["page"], 1);
            string sort = Utils.ObjectToStr(Request["sort"]);
            string order = Utils.ObjectToStr(Request["order"]);
            System.Data.DataTable list = formBll.GetList(itemId, beginTime, endTime, formState, pageIndex, pageSize, sort, order);
            int totalCount = formBll.GetCount(itemId, beginTime, endTime, formState);
            var JsonString = new StringBuilder();

            if (list.Rows.Count > 0)
            {
                JsonString.Append("[");
                for (int i = 0; i < list.Rows.Count; i++)
                {
                    JsonString.Append("{");
                    for (int j = 0; j < list.Columns.Count; j++)
                    {
                        if (j < list.Columns.Count - 1)
                        {
                            JsonString.Append("\"" + list.Columns[j].ColumnName.ToString() + "\":" + "\"" + list.Rows[i][j].ToString() + "\",");
                        }
                        else if (j == list.Columns.Count - 1)
                        {
                            JsonString.Append("\"" + list.Columns[j].ColumnName.ToString() + "\":" + "\"" + list.Rows[i][j].ToString() + "\"");
                        }
                    }

                    if (i == list.Rows.Count - 1)
                    {
                        JsonString.Append(",\"fieldList\":" + JsonConvert.SerializeObject(fvBll.Get_FORM_REFERENCE_VALUE_List(list.Rows[i]["ID"].ToString())) + "");
                        JsonString.Append("}");
                    }
                    else
                    {
                        JsonString.Append(",\"fieldList\":" + JsonConvert.SerializeObject(fvBll.Get_FORM_REFERENCE_VALUE_List(list.Rows[i]["ID"].ToString())) + "");
                        JsonString.Append("},");
                    }
                }
                JsonString.Append("]");
            }
            //string SS=JsonString.ToString();
            //return JsonString.ToString();

            StringBuilder jsonSb = new StringBuilder();
            jsonSb.Append("{");
            if (list != null && list.Rows.Count > 0)
            {
                jsonSb.Append(string.Format("\"total\":{0},\"rows\":{1}", totalCount, JsonString.ToString()));
            }
            else
            {
                jsonSb.Append("\"total\":0,\"rows\":[]");
            }
            //jsonSb.Append(string.Format("\"total\":{0},\"rows\":{1}", totalCount, JsonHandler.DataTableToJson(list)));
            jsonSb.Append("}");
            string json = jsonSb.ToString().Replace("\\", "").Replace("\"[", "").Replace("]\"", "");
            return json;
        }

        [SupportFilter(ActionName = "Index")]
        public string GetFiledList()
        {
            string itemId = Utils.ObjectToStr(Request["itemId"]);
            HC_ITEM_FIELD_VO fieldList = itemsBll.GetFieldInfoByItemId(itemId);
            return JsonConvert.SerializeObject(fieldList);
        }
        [SupportFilter(ActionName = "Index")]
        public string GetFormFiledValue()
        {
            string formId = Utils.ObjectToStr(Request["formId"]);
            string field = Utils.ObjectToStr(Request["field"]);
            FORM_REFERENCE_VALUE formValue = fvBll.Get_FORM_REFERENCE_VALUE(formId, field);
            return JsonConvert.SerializeObject(formValue);
        }

        [SupportFilter(ActionName = "Index")]
        public string GetExamineReason()
        {
            string formId = Utils.ObjectToStr(Request["formId"]);
            return examineBll.GetExamineReason(formId);
        }

        #region 创建
        [SupportFilter]
        public ActionResult Create()
        {
            string itemId = Utils.ObjectToStr(Request["itemId"]);
            //HC_ITEM_FIELD_VO fieldList = itemsBll.GetFieldInfoByItemId(itemId);
            //ViewBag.FieldList = fieldList;
            //ViewBag.itemId = itemId;
            //return View();
            List<V_HC_ITEM_FIELD_VALUE> fieldList = itemsBll.Get_FIELD_REFERENCE_VALUE_List(itemId);
            ViewBag.FieldList = fieldList;
            ViewBag.itemId = itemId;
            return View();
        }

        [HttpPost]
        [SupportFilter(ActionName = "Create")]
        public JsonResult Create(string pars = "")
        {
            string itemId = Utils.ObjectToStr(Request["itemId"]);
            HC_ITEM_FIELD_VO fieldList = itemsBll.GetFieldInfoByItemId(itemId);
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("ID", ResultHelper.NewId);
            dic.Add("ADDTIME", DateTime.Now);
            dic.Add("ADDUSER", GetUserId());
            dic.Add("UPDATETIME", null);
            dic.Add("UPDATEUSER", null);
            dic.Add("AUDITTIME", null);
            dic.Add("AUDITSER", null);
            dic.Add("STATE", 0);
            foreach (var item in fieldList.fieldListVo)
            {
                dic.Add(item.ExtendFieldNAME, Request[item.ExtendFieldNAME]);
            }
            if (dic != null && ModelState.IsValid)
            {
                string jsonStr = JsonConvert.SerializeObject(dic);
                if (formBll.DoAdd(itemId, dic))
                {
                    LogHandler.WriteServiceLog(GetUserId(), jsonStr, "成功", "创建", "HC/HC_FORM");
                    return Json(JsonHandler.CreateMessage(1, Resource.InsertSucceed));
                }
                else
                {
                    string ErrorCol = errors.Error;
                    LogHandler.WriteServiceLog(GetUserId(), jsonStr, "失败", "创建", "HC/HC_FORM");
                    return Json(JsonHandler.CreateMessage(0, Resource.InsertFail + ErrorCol));
                }
            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, Resource.InsertFail));
            }
        }
        #endregion

        #region 修改
        [SupportFilter]
        public ActionResult Edit()
        {
            string itemId = Utils.ObjectToStr(Request["itemId"]);
            string formId = Utils.ObjectToStr(Request["formId"]);
            List<HC_FORM_REFERENCE_VALUE_VO> fvList = fvBll.Get_FORM_REFERENCE_VALUE_List(formId);
            HC_ITEM_FIELD_VO fieldList = itemsBll.GetFieldInfoByItemId(itemId);
            ViewBag.FieldList = fvList;
            System.Data.DataTable entity = formBll.GetById(itemId, formId);
            ViewBag.FieldModel = entity;
            ViewBag.itemId = itemId;
            ViewBag.formId = formId;
            return View();
        }

        [HttpPost]
        [SupportFilter]
        public JsonResult Edit(string pars = "")
        {
            string itemId = Utils.ObjectToStr(Request["itemId"]);
            string formId = Utils.ObjectToStr(Request["formId"]);
            HC_ITEM_FIELD_VO fieldList = itemsBll.GetFieldInfoByItemId(itemId);
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("UPDATETIME", DateTime.Now);
            dic.Add("UPDATEUSER", GetUserId());
            foreach (var item in fieldList.fieldListVo)
            {
                dic.Add(item.ExtendFieldNAME, Request[item.ExtendFieldNAME]);
            }
            dic.Add("ID", formId);
            if (dic != null && ModelState.IsValid)
            {
                string jsonStr = JsonConvert.SerializeObject(dic);
                if (formBll.DoEdit(itemId, dic))
                {
                    LogHandler.WriteServiceLog(GetUserId(), jsonStr, "成功", "编辑", "HC/HC_FORM");
                    return Json(JsonHandler.CreateMessage(1, Resource.EditSucceed));
                }
                else
                {
                    string ErrorCol = errors.Error;
                    LogHandler.WriteServiceLog(GetUserId(), jsonStr, "失败", "编辑", "HC/HC_FORM");
                    return Json(JsonHandler.CreateMessage(0, Resource.EditFail + ErrorCol));
                }
            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, Resource.InsertFail));
            }
        }
        #endregion

        #region 详细 
        public ActionResult Details()//id 为AUDIT_ID
        {
            string itemId = Utils.ObjectToStr(Request["itemId"]);
            string formId = Utils.ObjectToStr(Request["formId"]);
            HC_ITEM_FIELD_VO fieldList = itemsBll.GetFieldInfoByItemId(itemId);
            ViewBag.FieldList = fieldList;
            System.Data.DataTable entity = formBll.GetById(itemId, formId);
            ViewBag.FieldModel = entity;
            ViewBag.itemId = itemId;
            ViewBag.formId = formId;
            return View(entity);
        }

        #endregion

        #region 审核
        [SupportFilter]
        public ActionResult Examine(string itemId, string formIds)
        {
            ViewBag.itemId = itemId;
            ViewBag.formIds = formIds;
            return View();
        }

        [HttpPost]
        [SupportFilter]
        public JsonResult Examine()
        {
            string itemId = Utils.ObjectToStr(Request["itemId"]);
            string formIds = Utils.ObjectToStr(Request["formIds"]);
            string state = Utils.ObjectToStr(Request["Examine"]);
            string ExamineRemark = Utils.ObjectToStr(Request["ExamineRemark"]);
            Dictionary<string, object> dic = new Dictionary<string, object>
            {
                { "itemId", itemId },
                { "formIds", formIds },
                { "STATE", state },
                { "AUDITSER", GetUserId() },
                { "ExamineRemark", ExamineRemark }
            };
            string jsonStr = JsonConvert.SerializeObject(dic);
            if (formBll.Examine(dic))
            {
                LogHandler.WriteServiceLog(GetUserId(), jsonStr, "成功", "报单审核", "HC/HC_Examine");
                return Json(JsonHandler.CreateMessage(1, "报单审核成功"));
            }
            else
            {
                string ErrorCol = errors.Error;
                LogHandler.WriteServiceLog(GetUserId(), jsonStr, "失败", "报单审核", "HC/HC_Examine");
                return Json(JsonHandler.CreateMessage(0, "报单审核失败" + ErrorCol));
            }
        }
        #endregion

        #region 导出
        [HttpPost]
        [SupportFilter(ActionName = "Export")]
        public JsonResult CheckExportData()
        {
            string itemId = Utils.ObjectToStr(Request["itemId"]);
            string beginTime = Utils.ObjectToStr(Request["beginTime"]);
            string endTime = Utils.ObjectToStr(Request["endTime"]);
            int formState = Utils.ObjToInt(Request["formState"], -2);
            DataTable list = formBll.GetList(itemId, beginTime, endTime, formState);
            HC_ITEM_FIELD_VO fieldList = itemsBll.GetFieldInfoByItemId(itemId);

            if (list != null && list.Rows.Count > 0)
            {
                return Json(JsonHandler.CreateMessage(1, "可以导出"));
            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, "没有可以导出的数据"));
            }
        }

        [SupportFilter]
        public ActionResult Export()
        {
            string itemId = Utils.ObjectToStr(Request["itemId"]);
            string beginTime = Utils.ObjectToStr(Request["beginTime"]);
            string endTime = Utils.ObjectToStr(Request["endTime"]);
            int formState = Utils.ObjToInt(Request["formState"], -2);
            DataTable list = formBll.GetList(itemId, beginTime, endTime, formState);
            HC_ITEM_FIELD_VO fieldList = itemsBll.GetFieldInfoByItemId(itemId);
            JArray jObjects = new JArray();
            decimal defValue = 0.00m;
            foreach (DataRow item in list.Rows)
            {
                var jo = new JObject();
                foreach (var fieldItem in fieldList.fieldListVo)
                {
                    if (fieldItem.CONTROL_TYPE == 1)
                    {
                        jo.Add(fieldItem.ExtendFieldTITLE, Utils.ObjectToStr(item[fieldItem.ExtendFieldNAME]));
                    }
                    else if (fieldItem.CONTROL_TYPE == 3)
                    {
                        jo.Add(fieldItem.ExtendFieldTITLE, Utils.ObjectToDateTime(item[fieldItem.ExtendFieldNAME]));
                    }
                    else
                        jo.Add(fieldItem.ExtendFieldTITLE, Utils.ObjToDecimal(item[fieldItem.ExtendFieldNAME], defValue));
                }
                jo.Add("报单录入时间", Utils.ObjectToDateTime(item["ADDTIME"]).ToString("yyyy-MM-dd HH:mm:ss"));
                if (Utils.ObjToInt(item["STATE"], 0) == 0)
                {
                    jo.Add("报单审核状态", "待审核");
                }
                else if (Utils.ObjToInt(item["STATE"], 0) == 1)
                {
                    jo.Add("报单审核状态", "审核通过");
                }
                else
                    jo.Add("报单审核状态", "审核未通过");
                jo.Add("报单审核时间", Utils.ObjectToDateTime(item["ADDTIME"]).ToString("yyyy-MM-dd HH:mm:ss"));

                jObjects.Add(jo);
            }
            var dt = JsonConvert.DeserializeObject<DataTable>(jObjects.ToString());
            var exportFileName = string.Concat(
                fieldList.itemVo.ITEM_TITLE,
                DateTime.Now.ToString("yyyyMMdd"),
                ".xlsx");
            return new ExportExcelResult
            {
                SheetName = "Sheet1",
                FileName = exportFileName,
                ExportData = dt
            };
        }
        #endregion

        #region 删除
        [HttpPost]
        [SupportFilter]
        public ActionResult Delete(string itemId, string id)
        {
            if (!string.IsNullOrWhiteSpace(itemId) && !string.IsNullOrWhiteSpace(id))
            {
                if (formBll.DoDelete(itemId, id))
                {
                    LogHandler.WriteServiceLog(GetUserId(), "ID:" + id, "成功", "删除", "HC_FORM");
                    return Json(JsonHandler.CreateMessage(1, Resource.DeleteSucceed));
                }
                else
                {
                    string ErrorCol = "【删除失败】";
                    LogHandler.WriteServiceLog(GetUserId(), "ID" + id + "," + ErrorCol, "失败", "删除", "HC_FORM");
                    return Json(JsonHandler.CreateMessage(0, Resource.DeleteFail + ErrorCol));
                }

            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, Resource.DeleteFail));
            }
        }
        #endregion
    }
}